#include "BreakBrick.h"

BreakBrick::BreakBrick(D3DXVECTOR2 position,EState state):GameObject(position, EObjectType::EBreakBrick,state)
{
	// this brick can view
	timeBeforDie = 0;
	// get texture
	CTexture *texture=ResourceManager::GetIns()->GetTexture(EResource::BrickBreak_ID);
	// init sprite from texture
	m_pSprite = new CSprite(texture);

	// add child-break-brick
	CRect rectSource=m_pSprite->GetBound();	
	float width=rectSource._width/4;
	float height = rectSource._height/4;
	float x=m_position.x;
	float y=m_position.y;

	// top left
	_childBreaks.push_back(new BreakBrickPart(D3DXVECTOR2(x-width, y+height),-1.3f,7));
	// bot left
	_childBreaks.push_back(new BreakBrickPart(D3DXVECTOR2(x-width, y-height), -2.4f, 7));
	// top right
	_childBreaks.push_back(new BreakBrickPart(D3DXVECTOR2(x+width, y+height), 1.3f, 7));
	// bot right
	_childBreaks.push_back(new BreakBrickPart(D3DXVECTOR2(x+width, y-height), 2.4f, 7));

	tmpPosY = m_position.y + 40;
};

void BreakBrick::Update(float dt)
{
	m_position += m_velocity*dt*60;
	// for real game
	if(m_state==EState::Hit || m_state == EState::Breaking)
	{
		m_state = EState::Breaking;
		timeBeforDie += dt;
		list<BreakBrickPart*>::iterator it;
		for(it=_childBreaks.begin(); it!=_childBreaks.end(); ++it)
		{
			(*it)->Update(dt);
		}
		if(timeBeforDie >= 1.0f)
			m_state = EState::Die;
	}

	if(m_state == EState::Move)
	{
		if(m_position.y < tmpPosY && m_velocity.y >=0)
		{
			m_velocity.y = 3;		
		}
		else
		{
			m_velocity.y = -3;
		}
		if(m_position.y < tmpPosY - 40)
		{
			m_position.y = tmpPosY - 40;
			m_state = EState::Alive;
			m_velocity.y = 0;
		}
	}
};

void BreakBrick::Draw()
{
	if(m_state == EState::Alive || m_state==EState::Move)
		GameObject::Draw();
	else if(m_state == EState::Hit || m_state == EState::Breaking)
	{
		list<BreakBrickPart*>::iterator it;
		for(it=_childBreaks.begin(); it!=_childBreaks.end(); ++it)
		{
			(*it)->Draw();
		}
	}
};

BreakBrick::~BreakBrick()
{
	GameObject::~GameObject();
};
